<?php
namespace sef;

class cache_file {
	private $path;
	protected function __construct() {
		$this -> path = TEMP_PATH;
	}

	public function set($key, $val) {
		file_put_contents($this -> path . md5($key), bin2hex(json_encode($val)));
	}

	public function get($key) {
		if (is_file($this -> path . md5($key))) {
			$val = json_decode(hex2bin(file_get_contents($this -> path . md5($key))), true);
			return $val;
		} else {
			return false;
		}
	}

}

class cache {
	public static $data = array();
	private $storage;

	protected function __construct($dirver = 'cache_file') {
		$this -> storage = new cache_file();
	}

	public function set($key, $val, $expired = null) {
		self::$data[$key]['val'] = $val;
		self::$data[$key]['expired'] = $expired;
		$this -> storage -> set($key, self::$data[$key]);
	}

	public function get($key) {
		if (!isset(self::$data[$key])) {
			$val = $this -> storage -> get($key);
		} else {
			$val = self::$data[$key];
		}

		if (isset($val)) {
			if ($val['expired'] > time()) {
				return $val['val'];
			} else {
				return false;
			}
		}
	}

	public function has($key) {
		return isset(self::$data[$key]);
	}

}
